// pages/statistics/order/index.js
import Toast from '../../../vant/toast/toast';
import { getOrderInfo, orderRefund } from '../../../utils/api/index.js';
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isOrderFruit:"",
    isIPhoneX: app.globalData.isIPhoneX,
    shippingMethodStr: {
      HOME: '宅配',
      STATION: '自提'
    },
    orderStatusStr: {
      CANCEL: '已取消',
      REFUSED: '系统拒绝',
      INCOMPLETE: '待完善',
      UNPAY: '未支付',
      PAID: '待打单',
      // PRINTED: '待揽收',
      PRINTED: '待发货',
      SHIPPED: '待收货',
      DELIVERING: '待收货',
      // RECEIVED: '已签收',
      RECEIVED: '已完成'

    },
    refundStatusStr: {
      CANCEL: '已取消',
      PENDING: '审核中',
      REFUNDED: '已退款',
      REFUSED: '已拒绝'
    },
    trackingStr: {
      CANCEL: '暂无物流信息',
      REFUSED: '暂无物流信息',
      INCOMPLETE: '暂无物流信息',
      UNPAY: '暂无物流信息',
      PAID: '暂无物流信息',
      PRINTED: '查看物流信息',
      // SHIPPED: '快递已从揽收点发出',
      SHIPPED: '快件已发出',

      DELIVERING: '快递正在配送中',
      // RECEIVED: '感谢您在果之道下单，欢迎您再次光临'
      RECEIVED: '已签收，欢迎您再次使用！'

    },
    trackingStrFruit: {
      CANCEL: '暂无物流信息',
      REFUSED: '暂无物流信息',
      INCOMPLETE: '暂无物流信息',
      UNPAY: '暂无物流信息',
      PAID: '暂无物流信息',
      PRINTED: '查看物流信息',
      // SHIPPED: '快递已从揽收点发出',
      SHIPPED: '快递已从揽收点发出',
      DELIVERING: '快递已从揽收点发出',
      // RECEIVED: '感谢您在果之道下单，欢迎您再次光临'
      RECEIVED: '快递已签收！'

    },
    isShowTrackingNo: false,
    orderId: '',

    refundOrderId:"",
    orderType:"",
    isShowRefund: false,
    isShowCancel: false,
    refundOperation: '',



    orderStatus: 'CANCEL',
    orderNo: '',
    fruitImageUrl:"",//水果图片
    createTime: '',
    largeBox: 0,
    smallBox: 0,
    shippingMethod: 'HOME',
    collectionName: '',
    contactName: '',
    stationCity: '',
    stationName: '',
    ticketCode: '',
    rangeCode:'',
    postage: 0,
    fruitTotalAmount:0,//水果金额
    deductibleAmount:0,//优惠券抵扣金额
    payAmount:0,//实际支付金额
    trackingNo: '',
    recipientName: '',
    phoneNumber: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    refundId: '',
    refundStatus: '',
    refundTime: '',
    maxRefundAmount: 0,
    refundAmount: 0,
    isShowRefundBtn: false,
    isShowCancelBtn: false,
    isShowComplain: false,
    username: '',
    expressType: '',
    avatarUrl: '', // 头像  客服需要
    customField: '',
    refundOperation: '',
    complainVible:false,

    trackingNoNum:1,//1是一个包裹,2是多个
    trackingNoData:[],//处理过的多个数据 是个数组

    orderNoNum:1,//1是一个包裹,2是多个
    orderNoData:[],//处理过的多个数据 是个数组

    complainStatus:null,
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId,
        refundOrderId: options.orderId,
        isOrderFruit:options.isOrderFruit,
      });
    }
    console.log(this.data.isOrderFruit);

    let comVisible= wx.getStorageSync('nowOrderstatus')
    this.setData({
      complainVible: comVisible
    })
    // wx.setStorageSync('nowOrderstatus', false)
    const userInfo = wx.getStorageSync('loginInfo');
    if (userInfo) {
      this.setData({
        avatarUrl: userInfo.avatarUrl
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let comVisible= wx.getStorageSync('nowOrderstatus')
    this.setData({
      complainVible: comVisible
    })
    // console.log(this.data.complainVible,'complainVible');
    // wx.setStorageSync('nowOrderstatus', false)
    this.getOrderInfo();
  },

  /**
   * 复制
   */
  toCopy(e) {
    console.log(e);
    // if(this.data.trackingNoNum==1||this.data.orderNoNum==1){
    //   wx.setClipboardData({
    //     data: this.data.trackingNo
    //   });
    // }else{
    //   wx.setClipboardData({
    //     data: e.currentTarget.dataset.data
    //   });

    // }

    wx.setClipboardData({
      data: e.currentTarget.dataset.data
    });
    
  },

  /**
   * 获取订单信息
   */
  getOrderInfo() {
    getOrderInfo({
      orderId: this.data.orderId
    }).then(res => {
      if (res.resultStatus) {
        console.log(res.resultData.complainStatus)
        this.setData({
          complainStatus:res.resultData.complainStatus?res.resultData.complainStatus:null
        })
        this.setOrderInfo(res.resultData);
        
      } else {
        Toast(res.errorMessage);
        this.setOrderInfo({});
      }
    });
  },

  /**
   * 设置订单数据
   */
  setOrderInfo(order) {
    // order.attributes = this.dealAttribute(order.attributes);
    this.setData({
      orderId: '',
      orderStatus: '',
      orderNo: '',
      fruitImageUrl:'',
      createTime: '',
      largeBox: 0,
      smallBox: 0,
      shippingMethod: 'HOME',
      collectionName: '',
      contactName: '',
      stationCity: '',
      stationName: '',
      ticketCode: '',
      rangeCode:'',
      postage: 0,
      fruitTotalAmount:0,//水果金额
      deductibleAmount:0,//优惠券抵扣金额
      payAmount:0,//实际支付金额
      trackingNo: '',
      recipientName: '',
      phoneNumber: '',
      province: '',
      city: '',
      district: '',
      detailAddress: '',
      refundId: '',
      refundStatus: '',
      refundTime: '',
      maxRefundAmount: 0,
      refundAmount: 0,
      username: '',
      expressType: '',
      ...order
    });
    if(this.data.trackingNo&&this.data.trackingNo.indexOf(";") != -1){
      let arr = this.data.trackingNo.split(';')
      this.setData({
         trackingNoNum:2,
         trackingNoData:arr,
       })
       console.log(this.data.trackingNoData);
     }
     if(this.data.orderNo&&this.data.orderNo.indexOf(";") != -1){
      let arr = this.data.orderNo.split(';')
      this.setData({
         orderNoNum:2,
         orderNoData:arr,
       })
       console.log(this.data.orderNoData);
     }

    let contactData = {
      订单ID: this.data.orderId,
      订单编号: this.data.orderNo,
      水果图片:this.data.fruitImageUrl,
      取票码: this.data.ticketCode,
      是否可以京配状态码: this.data.rangeCode,
      果农: this.data.username,
      收件人姓名: this.data.recipientName,
      收件人手机号: this.data.phoneNumber,
      规格: this.data.attributes,
      品种: this.data.fruitName,
      运费: this.data.postage / 100 + '元',
      水果金额:this.data.fruitTotalAmount/100+'元',
      优惠券:this.data.deductibleAmount / 100 + '元',
      实际支付金额:this.data.payAmount / 100 + '元',
      配送方式: this.data.shippingMethod === 'HOME' ? '宅配' : '自提',
      详细地址:
        this.data.province +
        this.data.city +
        this.data.district +
        this.data.detailAddress
    };
    this.setData({
      customField: JSON.stringify(contactData)
    });
    this.setData({
      isShowTrackingNo:
        ['SHIPPED', 'DELIVERING', 'RECEIVED', 'PRINTED'].indexOf(this.data.orderStatus) >
        -1
          ? true
          : false
    });
    if (
      ['SHIPPED', 'DELIVERING', 'RECEIVED', 'PRINTED'].indexOf(this.data.orderStatus) >
        -1 &&
      !order.complainStatus
    ) {
      this.setData({
        isShowComplain: true
      });
    }
    this.judgeShowRefundBtn();
  },

  // dealAttribute(attributes) {
  //   const tempArr = [];
  //   for (let a of attributes) {
  //     const attributeCombination = JSON.parse(a.attributeCombination)
  //       .map(item => {
  //         return item.attributeValue;
  //       })
  //       .join('');
  //     tempArr.push(`${attributeCombination}${a.quantity}箱`);
  //   }
  //   return tempArr.join(',');
  // },

  judgeShowRefundBtn() {
    if (this.data.refundId) {
      if (this.data.refundStatus === 'CANCEL') {
        if (this.data.orderStatus === 'PAID') {
          this.setData({
            isShowRefundBtn: true,
            isShowCancelBtn: false
          });
        }
      } else if (this.data.refundStatus === 'PENDING') {
        this.setData({
          isShowRefundBtn: false,
          isShowCancelBtn: true
        });
      } else {
        this.setData({
          isShowRefundBtn: false,
          isShowCancelBtn: false
        });
      }
    } else {
      if (this.data.orderStatus === 'PAID') {
        this.setData({
          isShowRefundBtn: true,
          isShowCancelBtn: false
        });
      }
    }
  },

  // /**
  //  * 申请/取消退款
  //  */
  // toRefund(e) {
  //   const refundOperation = e.currentTarget.dataset.type;
  //   orderRefund({
  //     orderId: this.data.orderId,
  //     refundOperation
  //   }).then(res => {
  //     if (res.resultStatus) {
  //       Toast(refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
  //       this.getOrderInfo(this.data.orderId);
  //     } else {
  //       Toast(res.errorMessage);
  //     }
  //   });
  // },

  // 申请/取消退款
  // toRefund(e) {
  //   const orderId = this.data.orderId;
  //   const refundStatus =  e.currentTarget.dataset.type;
  //   if (!refundStatus || refundStatus === 'CANCEL') {
  //     // 申请
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: refundStatus,
  //       refundOrderId: orderId
  //     })

  //   } else {
  //     // 取消
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: refundStatus,
  //       refundOrderId: orderId
  //     })
  //   }
  // },

  // handleAction(data) {
  //   if (data.detail === 'ok' && this.data.refundOrderId && this.data.refundOperation) {
  //     this.setData({
  //       refundPopupShow: false
  //     })
  //     orderRefund({
  //       orderId: this.data.refundOrderId,
  //       refundOperation: this.data.refundOperation,
  //     }).then(res => {
  //       if (res.resultStatus) {
  //         Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
  //         this.getOrderInfo(this.data.orderId);
  //       } else {
  //         Toast(res.errorMessage);
  //       }
  //     })
  //   } else {
  //     this.setData({
  //       refundPopupShow: false,
  //       refundOperation: ''
  //     })
  //   }
  // },



 //取消退款
    toRefund(e){
      const orderType = e.currentTarget.dataset.type

      if(orderType=="CANCEL"){
        this.setData({
          isShowCancel:true,
          refundOperation: "CANCEL",
        })
      }else{
        this.setData({
          isShowRefund:true,
          refundOperation: "REFUND",
        })

      }

     
    },


   //取消
   onClose() {
    this.setData({
      isShowRefund: false
    });
  },

  // 确定
  onSubmit() {
    orderRefund({
      orderId: this.data.refundOrderId,
      refundOperation: this.data.refundOperation,
    }).then(res => {
      if (res.resultStatus) {
        Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
        this.setData({
          isShowRefund: false
        });
        this.onShow()
      } else {
        Toast(res.errorMessage);
      }
    })
  },

  //取消
  onClose1() {
    this.setData({
      isShowCancel: false
    });
  },

  // 确定
  onSubmit1() {
    orderRefund({
      orderId: this.data.refundOrderId,
      refundOperation: this.data.refundOperation,
    }).then(res => {
      if (res.resultStatus) {
        Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
        this.setData({
          isShowCancel: false
        });
        this.onShow()

      } else {
        Toast(res.errorMessage);
      }
    })
  },






  toTracking() {
    if (this.data.trackingNo && this.data.isShowTrackingNo) {
      wx.navigateTo({
        url:
          '/pages/statistics/logistics/index?orderId=' +
          this.data.orderId +
          '&expressType=' +
          this.data.expressType
      });
    }
  },

  toComplaint() {
    wx.navigateTo({
      url: '/pages/statistics/complaint/index?orderId=' + this.data.orderId + '&orderNo=' + this.data.orderNo
    });
  },

  handleContact(e) {
    console.log(e);
    console.log(e.detail.query);
  },
  // toPageIndex(){
  //   wx.navigateTo({
  //     url: '/pages/statistics/complaint',
  //   })
  // }
  
});
